# coding:utf-8
__author__ = 'kony'

import paramiko
from base.models import Worker

def ssh_login(ip, username, passwd):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip, 22, username, passwd)
    return ssh

def run_locust(self, project, scene_type, workers, params):
    ips = workers.split(',')
    for ip in ips:
        account = Worker.objects.filter(project = self.project, ip = ip).values("username", "password")
        username = account[0]['username']
        passwd = account[0]['password']
        ssh = ssh_login(ip, username, passwd)
        if scene_type == 'single':
            cmd = f'cd ../project/{project}/scripts;nohup locust -f single.py {params} --worker --master-host=10.12.15.104 &'
        elif scene_type == 'mixed':
            cmd = f'cd ../project/{project}/scripts;nohup locust -f mixed.py {params} --worker --master-host=10.12.15.104 &'
        stdin, stdout, stderr = ssh.exec_command(cmd)
        print(stdout)
